package com.slg.android.manyanime.fragment;


import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.slg.android.manyanime.AdActivity;
import com.slg.android.manyanime.AnimationDetailActivity;
import com.slg.android.manyanime.R;
import com.slg.android.manyanime.adapter.AnimeRecommendAdapter;
import com.slg.android.manyanime.bean.Animation;
import com.slg.android.manyanime.utils.ApiUtils;
import com.slg.android.manyanime.utils.NetUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class AnimeRecommendFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2<ListView>, AdapterView.OnItemClickListener {
    @ViewInject(R.id.common_loading)
    private RelativeLayout loading;
    @ViewInject(R.id.common_loading_image)
    private ImageView loadingImage;
    @ViewInject(R.id.anime_recommend_pullToRefreshListView)
    private PullToRefreshListView pullToRefreshListView;
    private android.view.animation.Animation loadingAnimation;
    private ListView listView;
    private String json;
    private int currentPage = 1;
    private int totalCount;
    private List<Animation> data;
    private final String SHARED_JSON = "AnimeRecommendJsonData";
    private SharedPreferences sharedPreferences;
    private HttpUtils utils;
    private AnimeRecommendAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FragmentActivity activity = getActivity();
        sharedPreferences = activity.getSharedPreferences("JSON", activity.MODE_PRIVATE);
        json = sharedPreferences.getString(SHARED_JSON, null);
        data = new ArrayList<>();
        utils = new HttpUtils();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_anime_recommend, container, false);
        ViewUtils.inject(this, view);
        listView = pullToRefreshListView.getRefreshableView();
        listView.setOnItemClickListener(this);
        pullToRefreshListView.setOnRefreshListener(this);
        pullToRefreshListView.setMode(PullToRefreshBase.Mode.BOTH);
        if (json == null) {
            //监测网络
            if (NetUtil.isConnectInternet(getActivity())) {
                loading.setVisibility(View.VISIBLE);
                loadingAnimation = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_common_rotate);
                loadingImage.startAnimation(loadingAnimation);
                utils.send(HttpRequest.HttpMethod.GET
                        , ApiUtils.ANIMATION_RECOMMEND + "1"
                        , new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        setData(objectResponseInfo.result);
                        loadingAnimation.cancel();
                        loading.setVisibility(View.GONE);
                        adapter = new AnimeRecommendAdapter(getActivity(), data);
                        listView.setAdapter(adapter);
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        loadingAnimation.cancel();
                        loading.setVisibility(View.GONE);
                        Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT)
                                .show();
                        Log.e("网络异常", "s", e);
                    }
                });

            } else {//当前未连接网络
                Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT)
                        .show();
            }

        } else {
            try {
                parseData(json);
                adapter = new AnimeRecommendAdapter(getActivity(), data);
                listView.setAdapter(adapter);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return view;
    }

    private void parseData(String d) throws JSONException {
        JSONObject jsonObject = new JSONObject(json);
        totalCount = jsonObject.getInt("count");
        JSONArray list = jsonObject.getJSONArray("list");
        for (int i = 0; i < list.length(); i++) {
            JSONObject animationJson = list.getJSONObject(i);
            Animation animation = new Animation();
            data.add(animation.parseAnimation(animationJson));
        }
    }

    private void setData(String result) {
        json = result;
        try {
            parseData(json);
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putString(SHARED_JSON, json);
            edit.commit();
        } catch (JSONException e) {
            Log.e("解析异常", "AnimeRecommend解析异常", e);
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (refreshView.isRefreshing()) {
            if (NetUtil.isConnectInternet(getActivity())) {
                utils.send(HttpRequest.HttpMethod.GET
                        , ApiUtils.ANIMATION_RECOMMEND + "1"
                        , new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                        currentPage = 1;
                        data.clear();
                        setData(objectResponseInfo.result);
                        adapter.notifyDataSetChanged();
                        pullToRefreshListView.onRefreshComplete();
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        pullToRefreshListView.onRefreshComplete();
                        Log.e("网络异常", "s", e);
                    }
                });
            } else {//当前未连接网络
                Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT)
                        .show();
                pullToRefreshListView.onRefreshComplete();
            }
        }

    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        if (refreshView.isRefreshing()) {
            if (currentPage * 10 >= totalCount) {
                Toast.makeText(getActivity(), "没有更多内容了", Toast.LENGTH_SHORT).show();
                pullToRefreshListView.onRefreshComplete();
            } else {
                if (NetUtil.isConnectInternet(getActivity())) {
                    currentPage++;
                    utils.send(HttpRequest.HttpMethod.GET
                            , ApiUtils.ANIMATION_RECOMMEND + currentPage
                            , new RequestCallBack<String>() {
                        @Override
                        public void onSuccess(ResponseInfo<String> objectResponseInfo) {
                            setData(objectResponseInfo.result);
                            adapter.notifyDataSetChanged();
                            pullToRefreshListView.onRefreshComplete();
                        }

                        @Override
                        public void onFailure(HttpException e, String s) {
                            pullToRefreshListView.onRefreshComplete();
                            Log.e("网络异常", "s", e);
                        }
                    });

                } else {//当前未连接网络
                    Toast.makeText(getActivity(), R.string.no_network, Toast.LENGTH_SHORT)
                            .show();
                    pullToRefreshListView.onRefreshComplete();
                }
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        int headerViewsCount = listView.getHeaderViewsCount();
        Animation animation = data.get(position - headerViewsCount);
        String isAd = animation.getIsAd();
        //广告跳转webView
        if("1".equals(isAd)){
            Intent intent = new Intent(getActivity(), AdActivity.class);
            intent.putExtra("title",animation.getName());
            intent.putExtra("url",animation.getId());
            startActivity(intent);
        }else{//非广告跳转动画详情
            Intent intent = new Intent(getActivity(), AnimationDetailActivity.class);
            intent.putExtra("id",animation.getId());
            startActivity(intent);
        }

    }
}
